<template>
    <div>
        <h-section title="近期未登录用户统计" collapse>
            <div class="form-cont">
                <flexbox style="font-size: 13px">
                    <span class="margin-r-16">选择时间段：</span>
                    <a-select v-model:value="timeType" style="width: 200px" class="margin-r-8" @change="handleSelectTimeChange">
                        <a-select-option key="1">近七天</a-select-option>
                        <a-select-option key="2">近一月</a-select-option>
                        <a-select-option key="3">近三月</a-select-option>
                    </a-select>
                </flexbox>

                <a-divider />

                <flexbox>
                    <div :class="['card-item', currIndex === 0 ? 'active-1-bg' : 'border']" @click="currIndex = 0">
                        <flexbox style="margin-top: 24px; margin-left: 26px">
                            <img style="width: 18px; height: 18px" src="@/assets/images/yonghutongji/user-3.png" />
                            <span style="font-size: 14px" :class="[currIndex === 0 ? 'active-1-text' : '', 'margin-l-8']">
                                {{ `${timeTypeFilter(timeType)}未登录用户数` }}
                            </span>
                        </flexbox>
                        <span style="position: absolute; top: 24px; right: 68px; font-size: 36px">
                            {{ paginationConfig.total }}
                        </span>
                    </div>
                </flexbox>

                <flexbox justify="space-between" style="font-size: 12px; margin-top: 24px">
                    <flexbox>
                        <span class="margin-l-16 margin-r-16">团队：</span>
                        <h-cascader
                            placeholder="请选择"
                            :options="subTeamOptions"
                            labelField="name"
                            valueField="id"
                            show-search
                            :change-on-select="true"
                            childrenField="subList"
                            @change="handleCascaderChange"
                        ></h-cascader>

                        <a-button class="margin-l-8" @click="handleSubmit">筛选</a-button>
                    </flexbox>
                    <a-button type="primary" class="margin-l-8" @click="exportFile">导出</a-button>
                </flexbox>
            </div>

            <div class="margin-t-16">
                <a-table
                    rowKey="id"
                    size="small"
                    :loading="loading"
                    :columns="tableColumns"
                    :data-source="list"
                    :pagination="paginationConfig"
                    @change="handleTableChange"
                >
                    <template #customTitle>
                        {{ `${timeTypeFilter(timeType)}未登录用户` }}
                    </template>
                    <template #index="{ index }">
                        {{ index + 1 }}
                    </template>
                </a-table>
            </div>
        </h-section>
    </div>
</template>

<script lang="ts" >
import api from '@/api';
import { ref, reactive, defineComponent, toRefs } from 'vue';
import moment from 'moment';
import { downByBlob } from '@/utils/file/downFile';
import { HCascader } from '@/components';
import { useTableLoading, usePagination } from '@/components/Table/hooks';
export default defineComponent({
    components: {
        HCascader
    },
    setup() {
        const { loading, setLoading } = useTableLoading();
        const { paginationConfig, setPaginationConfig } = usePagination();
        const timeType = ref<any>('1');
        const subTeamOptions = ref<any>([]);
        const list = ref<any>([]);
        const state = reactive<any>({
            startTime: null,
            endTime: null,
            departmentId: '',
            teamId: ''
        });
        const currIndex = ref<number>(0);
        const tableColumns = [
            {
                title: '序号',
                slots: { customRender: 'index' }
            },
            {
                dataIndex: 'empName',
                slots: { title: 'customTitle' }
            }
        ];
        const timeTypeFilter = (val) => {
            switch (val) {
                case '1':
                    return '近七天';
                case '2':
                    return '近一月';
                case '3':
                    return '近三月';
            }
        };
        const getList = async () => {
            setLoading(true);
            const query = {
                pageNum: paginationConfig.value.current,
                pageSize: paginationConfig.value.pageSize,
                startTime: state.startTime,
                endTime: state.endTime,
                departmentId: state.departmentId,
                teamId: state.teamId
            };
            const { success, moule, totalCount } = await api.userActionModel.getNoneLoginUser(query);
            if (success) {
                list.value = moule.map((item, index) => {
                    const obj = {};
                    if (item.unitConsumingTime) {
                        Object.keys(item.unitConsumingTime).forEach((key: any) => {
                            if (key !== '0') {
                                obj[`month${key}`] = item.unitConsumingTime[key];
                            }
                        });
                    }
                    return {
                        ...item,
                        ...obj,
                        id: index
                    };
                });
                setPaginationConfig({
                    total: totalCount
                });
            }
            setLoading(false);
        };
        const handleSubmit = async () => {
            getList();
        };
        const handleSelectTimeChange = (val) => {
            switch (val) {
                case '1':
                    state.startTime = moment().subtract(7, 'days').format('YYYY-MM-DD HH:mm:ss');
                    state.endTime = moment().format('YYYY-MM-DD HH:mm:ss');
                    break;
                case '2':
                    state.startTime = moment().subtract(1, 'months').format('YYYY-MM-DD HH:mm:ss');
                    state.endTime = moment().format('YYYY-MM-DD HH:mm:ss');
                    break;
                case '3':
                    state.startTime = moment().subtract(3, 'months').format('YYYY-MM-DD HH:mm:ss');
                    state.endTime = moment().format('YYYY-MM-DD HH:mm:ss');
                    break;
                default:
                    '';
            }
            getList();
        };
        const handleCascaderChange = ({ nodeArr }) => {
            paginationConfig.value.current = 1;
            paginationConfig.value.pageSize = 20;
            if (nodeArr.length) {
                state.departmentId = nodeArr[0];
                if (nodeArr.length > 1) {
                    state.teamId = nodeArr[nodeArr.length - 1];
                } else {
                    const target = subTeamOptions.value.find((item) => item.id === state.departmentId);
                    if (target) {
                        state.teamId = target.subList.map((item) => item.id).join(',');
                    }
                }
            } else {
                state.teamId = '';
                state.departmentId = '';
            }
        };
        const getOrgTree = async () => {
            const formData: any = new FormData();
            formData.append('architectureType', '行政组织');
            const { success, moule } = await api.portalControlModel.getOrganizationTree(formData);
            if (success) {
                if (moule && moule.length) {
                    subTeamOptions.value = moule[0].subList[0].subList;
                }
            }
        };
        const exportFile = async () => {
            const query = {
                pageNum: paginationConfig.value.current,
                pageSize: paginationConfig.value.pageSize,
                startTime: state.startTime,
                endTime: state.endTime,
                departmentId: state.departmentId,
                teamId: state.teamId
            };
            const res = await api.userActionModel.noneLoginUserDown(query, { responseType: 'blob' });
            res && downByBlob(res, `${timeTypeFilter(timeType.value)}未登录用户统计` + '.xls');
        };
        const handleTableChange = (val) => {
            paginationConfig.value = val;
            getList();
        };
        const init = () => {
            handleSelectTimeChange('1');
            getOrgTree();
        };
        init();

        return {
            handleTableChange,
            handleCascaderChange,
            exportFile,
            handleSubmit,
            currIndex,
            tableColumns,
            loading,
            handleSelectTimeChange,
            paginationConfig,
            timeTypeFilter,
            ...toRefs(state),
            timeType,
            list,
            subTeamOptions
        };
    }
});
</script>

<style scoped lang="less">
.active-1-bg {
    background-color: #f7f8ff;
}
.active-1-text {
    color: #2359dd;
}
.border {
    border: 1px solid #e9e9e9 !important;
}
.card-item {
    width: 306px;
    height: 98px;
    position: relative;
    cursor: pointer;
    border: 1px solid transparent;
}
.form-cont {
    ::v-deep(.ant-select-selector) {
        height: 31px !important;
    }
}
</style>